package edu.uci.hm.util;

import java.security.MessageDigest;
import java.util.zip.CRC32;

/**
 * Copyright (C) 2009.
 * @author Yasser Ganjisaffar <yganjisa at uci dot edu>
 */

public final class Cryptography {
	
	private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	public static String MD5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			return hexStringFromBytes(md.digest());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public static long CRC32(String str) {
		CRC32 crc32 = new CRC32();		
		crc32.update(str.getBytes());
        return crc32.getValue();
	}
	
	private static String hexStringFromBytes(byte[] b) {
		String hex = "";
		int msb;
		int lsb = 0;
		int i;

		// MSB maps to idx 0
		for (i = 0; i < b.length; i++) {
			msb = ((int) b[i] & 0x000000FF) / 16;
			lsb = ((int) b[i] & 0x000000FF) % 16;
			hex = hex + hexChars[msb] + hexChars[lsb];
		}
		return (hex);
	}
	
	public static void main(String[] args) {
		System.out.println(CRC32("http://tebyan.net"));
	}
}
